package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Date;
import java.util.Calendar;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import Database.DatabaseConnector;

@WebServlet("/DeleteTimeSheetServlet")
public class DeleteTimeSheetServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		DatabaseConnector db = new DatabaseConnector();
		boolean failed = false;
		
		try {
			long jobID = Long.parseLong(request.getParameter("jobID"));
			long empID = Long.parseLong(request.getParameter("empID"));
			
			Calendar calendar = Calendar.getInstance();
			String[] dateString = request.getParameter("date").split("-");
			calendar.set(Integer.parseInt(dateString[0]), Integer.parseInt(dateString[1])-1, Integer.parseInt(dateString[2]));
			Date date = new Date(calendar.getTimeInMillis());
			
			db.removeTimeSheet(empID, jobID, date);
			
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		} catch (NullPointerException e) {
			failed = true;
		} catch (NumberFormatException e) {
			failed = true;
		} catch (ArrayIndexOutOfBoundsException e) {
			failed = true;
		}
		
		JSONObject result = new JSONObject();
		try {
			result.put("failed", failed);
			response.getWriter().print(result);
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		} catch (JSONException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		} catch (IOException e) {
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		
		
	}
}
